import CryptoJS from "crypto-js";

const DEFAULT_KEY = "fYAh-YjXqJDUGTnjQ4Txb4VuYaMIQJ52";

// const mode = CryptoJS.mode.ECB;
const cryptoMode = CryptoJS.mode.ECB;
// const cryptoMode = CryptoJS.mode.CBC;

export default {
  encrypt(plaintext, key = DEFAULT_KEY) {
    const keyHex = CryptoJS.enc.Utf8.parse(key);
    const ivHex = CryptoJS.enc.Utf8.parse(key.slice(0, 16)); // 取前16字节作为IV

    const encrypted = CryptoJS.AES.encrypt(plaintext, keyHex, {
      iv: ivHex,
      mode: cryptoMode,
      padding: CryptoJS.pad.Pkcs7,
    });

    return encrypted.toString();
  },
  aesEcbEncrypt(plainText, key = DEFAULT_KEY) {
    // 将密钥转换为WordArray
    const keyBytes = CryptoJS.enc.Utf8.parse(key);

    // 加密配置
    const encrypted = CryptoJS.AES.encrypt(plainText, keyBytes, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });

    // 返回Base64格式的密文
    return encrypted.toString();
  },
  /**
   * AES解密
   * @param {string} ciphertext 密文(Base64格式)
   * @param {string} key 密钥(可选)
   * @returns {string} 解密后的原文
   */
  decrypt(ciphertext, key = DEFAULT_KEY, mode = cryptoMode) {
    // console.log("mode--: ", mode);
    const keyHex = CryptoJS.enc.Utf8.parse(key);
    const ivHex = CryptoJS.enc.Utf8.parse(key.slice(0, 16));

    const decrypted = CryptoJS.AES.decrypt(ciphertext, keyHex, {
      iv: ivHex,
      mode,
      padding: CryptoJS.pad.Pkcs7,
    });

    return decrypted.toString(CryptoJS.enc.Utf8);
  },
};
